<?php
	include_once "db/db.php";
	if (!isset($current_game)) {
		header("location:load.php?recentgame=true");
	}
	
	/* Contents */

	include_once "header.php";
	
	function car_html($colour, $gender, $married, $children) {
		$html = "<div class=\"car\">"
				. "<img src=\"images/car/car.png\" style=\"background-color:$colour;\"/>"
				. "<img class=\"layer\" src=\"images/car/pos1" . ($gender == "0" ? "m" : "f") . ".png\"/>";
		// Spouse
		if ($married) {
			$html .= "<img class=\"layer\" src=\"images/car/pos2" . ($gender == "0" ? "f" : "m") . ".png\"/>";
		}
		// Children
		foreach ($children as $index => $child) {
			$html .= "<img class=\"layer\" src=\"images/car/pos" . ($index+3) . ($child['gender'] == "0" ? "m" : "f") . ".png\"/>";
		}
		// Steering wheel
		$html .= "<img class=\"layer\" src=\"images/car/car_steering.png\"/>";
		return $html . "</div>";
	}
	
	// Load configuration
	$config_array = get_settings();
	
	// Find if the game is over
	$game_over_array = mysql_fetch_assoc(mysql_query("
		SELECT 
			COUNT(`gameplayer`.`player`) AS `players`, 
			COUNT(`gameplayer`.`retired`) AS `retirees`
		FROM `gameplayer` 
		WHERE `gameplayer`.`game` = '$current_game_id'
		GROUP BY `gameplayer`.`game`
		LIMIT 1"));
	$game_over = ($game_over_array['players'] == $game_over_array['retirees']);
	$show_results = ($game_over && $current_game['turn'] == "");
?>

<script type="text/javascript">
	jQuery(document).ready(function () {
		
		var loadDialog = function (type, loadFunction) {
			var dialog = jQuery("#dialog-" + type);
			if (dialog.length == 0) {
				jQuery("#dialog-load").load("play-load.php", {"type":type}, function () {
					jQuery(this).find(".dialog").appendTo("#dialogs").dialog({
						autoOpen: true,
						modal: true,
						width: 550
					}).find("input[type='reset']").click(function () {
						jQuery(this).parentsUntil(".dialog").parent().dialog("close");
					}).end().find("table.cards").cards();
					// Custom load function
					if (typeof loadFunction === "function") {
						loadFunction();
					}
				});
			} else {
				dialog.dialog("open");
			}
		};
		
		jQuery("#btnMoney").click(function () {
			loadDialog("money", function () {
				jQuery("#dialog-money input:text.money").money();
				jQuery("#moneyRowAmount, #moneyRowCareer, #moneyRowEvent").hide();
				jQuery("#dialog-money input:radio[name='moneyAction']").change(function () {
					var val = jQuery(this).val();
					if (val == "payday" || val == "taxes" || val == "") {
						jQuery("#moneyRowAmount, #moneyRowCareer, #moneyRowEvent").hide();
					} else if (val == "earn") {
						jQuery("#moneyRowAmount, #moneyRowEvent").show();
						jQuery("#moneyRowCareer").hide();
						jQuery("#moneyInputAmount").val("").change().focus();
					} else if (val == "pay") {
						jQuery("#moneyRowAmount, #moneyRowCareer, #moneyRowEvent").show();
						jQuery("#moneyInputAmount").val("-").change().focus();
					}
				});
			});
		});
		jQuery("#btnCareerIncome").click(function () {
			loadDialog("career-income");
		});
		jQuery("#btnFamily").click(function () {
			loadDialog("family");
		});
		jQuery("#btnHouse").click(function () {
			loadDialog("house");
		});
		jQuery("#btnLifeCard").click(function () {
			loadDialog("lifecard");
		});
		jQuery("#btnRetire").click(function () {
			loadDialog("retire");
		});
		
		jQuery("#btnInsurance").click(function () {
			loadDialog("insurance");
		});
		jQuery("#btnStocks").click(function () {
			loadDialog("stocks");
		});
		
		jQuery("#btnPrevTurn").click(function () {
		});
		jQuery("#btnNextTurn").click(function () {
		});
		
		/* Dialogs */
		jQuery("div.dialog").dialog({
			autoOpen: false,
			modal: true,
			width: 500
		}).find("input[type='reset']").click(function () {
			jQuery(this).parentsUntil("div.dialog").parent().dialog("close");
		});
	});
</script>
<script type="text/javascript" src="js/cards.js"></script>
<link rel="stylesheet" type="text/css" href="css/cards.css"/>

<?php
	if ($show_results) {
		echo "<h2>Congratulations !</h2>";
	}
?>

<form action="play-actions.php" method="post" class="play-actions">
	<?php if ($game_over && !$show_results) { ?>
	<input type="submit" value="END OF GAME - See Results..." name="endGameSubmit" />
	<?php } elseif(!$game_over) { ?>
	
	<input type="button" value="$$$" id="btnMoney"/>
	<input type="button" value="Career/Income" id="btnCareerIncome"/>
	<input type="button" value="Family" id="btnFamily"/>
	<input type="button" value="House" id="btnHouse"/>
	<input type="button" value="Life card" id="btnLifeCard"/>
	<input type="button" value="Retire" id="btnRetire"/>
	
	<!--
	<span class="divide">&nbsp;</span>
	
	<input type="button" value="Insurance" id="btnInsurance"/>
	<input type="button" value="Stocks" id="btnStocks"/>
	-->
	
	<span class="divide">&nbsp;</span>

	<input type="submit" name="prevTurn" value="&lt;" id="btnPrevTurn"/><input type="submit" name="nextTurn" value="Next turn &gt;&gt;" id="btnNextTurn"/>
	<?php } ?>
</form>

<table class="play"><tr>
<?php
	// Players
	$player_query = mysql_query("
		SELECT `player`.*, `gameplayer`.*, 
			`house`.`name` AS `housename`, `income`.`income` AS `income`,
			`career`.`name` AS `careername`, 
			SUM(`cash`.`amount`) AS `cashInHand`,
			`retirementhome`.`name` AS `retirementhome`,
			`gameplayer`.`retired` IS NOT NULL AS `isretired`,
			`retirementhome`.`lifecardssafe` AS `lifecardssafe`
		FROM `gameplayer` 
			LEFT JOIN `player` ON (`gameplayer`.`player` = `player`.`id`)
			LEFT JOIN `house` ON (`gameplayer`.`house` = `house`.`id`)
			LEFT JOIN `income` ON (`gameplayer`.`income` = `income`.`id`)
			LEFT JOIN `career` ON (`gameplayer`.`career` = `career`.`id`)
			LEFT JOIN `cash` ON (`cash`.`game` = '$current_game_id' AND `player`.`id` = `cash`.`player`)
			LEFT JOIN `retirementhome` ON (`gameplayer`.`retired` = `retirementhome`.`id`)
		WHERE `gameplayer`.`game` = '$current_game_id'
		GROUP BY `player`.`id`
		ORDER BY `player`.`name`
		");
	while ($player = mysql_fetch_assoc($player_query)) {
		$playerid = $player['id'];
		// Children
		$children = array();
		$children_query = mysql_query("
				SELECT * FROM `playerfamily` 
				WHERE `player` = '$playerid' AND `game` = '$current_game_id'
				ORDER BY `datetime`");
		while ($child = mysql_fetch_assoc($children_query)) {
			array_push($children, $child);
		}
		// Life cards
		$lifecards = array();
		$lifecards_query = mysql_query("
			SELECT `lifecard`.*, `playerlifecard`.`datetime` 
			FROM `playerlifecard` LEFT JOIN `lifecard` ON (`playerlifecard`.`lifecard` = `lifecard`.`id`)
			WHERE `playerlifecard`.`game` = '$current_game_id'
				AND `playerlifecard`.`player` = '$playerid'
			ORDER BY `datetime`");
		while ($lifecard = mysql_fetch_assoc($lifecards_query)) {
			array_push($lifecards, $lifecard);
		}
		// Loan
		$loan_total = mysql_result(mysql_query("
				SELECT SUM(`amount`) FROM `cash` 
				WHERE `game` = '$current_game_id' AND `player` = '$playerid' AND `event` LIKE 'LOAN%'"), 0);
		// Results
		if ($show_results) {
			$lifecard_prize_money = mysql_result(mysql_query("
					SELECT SUM(`lifecard`.`prize`) 
					FROM `playerlifecard` LEFT JOIN `lifecard` ON (`playerlifecard`.`lifecard` = `lifecard`.`id`)
					WHERE `playerlifecard`.`game` = '$current_game_id' 
						AND `playerlifecard`.`player` = '$playerid'"), 0);
			$grand_total_money = $player['cashInHand'] + $config_array['initialcash'] + $lifecard_prize_money;
		}
		// Output
		echo "
			<td class=\"player" . ($current_game['turn'] == $player['id'] ? " player-turn" : "") . "\">
				" . ($show_results ? "<span class=\"results\">" . format_money($grand_total_money) . "</span>" : "") . "
				<span class=\"name\">" . $player['name'] . "</span>
				<span class=\"car\">" . car_html($player['colour'], $player['gender'], $player['married'], $children) . "</span>
				<span class=\"cash\">
					<a class=\"report\" 
							href=\"report-transactions.php?player=" . $player['id'] . "\">" . 
						format_money($player['cashInHand'] + $config_array['initialcash']) . "</a>
					" . ($loan_total > 0 ? 
							"<span class=\"cash-loan\">(borrowed " . format_money($loan_total) . ")</span>" : "") . "
				</span>
				<span class=\"house\">House: " . $player['housename'] . "</span>
				" . ($player['careername']=="" || $player['isretired'] ? "" : 
						"<span class=\"career\">" . 
							$player['careername'] . "; earning " . 
							format_money($player['income']) . 
						"</span>") . "
				" . ($player['isretired'] ? 
						"<span class=\"retired\">Retired to " . $player['retirementhome'] . "</span>" : "") . "
				<span class=\"lifecards\">" . lifecards_html($lifecards, $show_results) . "</span>
			</td>";
	}
?>
</tr></table>

<div id="dialog-load"></div>
<div id="dialogs"></div>

<?php
	include_once "footer.php";
?>
